package com.dance.webflux;

import com.dance.webflux.handler.UserHandler;
import com.dance.webflux.service.impl.UserServiceImpl;
import org.springframework.boot.autoconfigure.rsocket.RSocketProperties;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

public class FunctionServer {

    /**
     * 创建路由
     * @return 路由函数
     */
    public RouterFunction<ServerResponse> routingFunction(){
        // 创建UserService
        UserServiceImpl userService = new UserServiceImpl();
        // 创建处理器
        UserHandler userHandler = new UserHandler(userService);
        // 设置路由
        return RouterFunctions
                .route(GET("/user/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUserById)
                .andRoute(GET("/users").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUserAll)
                .andRoute(POST("/saveUserInfo"), userHandler::saveUserInfo);
    }

    /**
     * 创建服务器完成适配
     */
    public void createReactorServer(){
        // 路由和Handler适配
        RouterFunction<ServerResponse> serverResponseRouterFunction = routingFunction();
        // 转换为HttpHandler
        HttpHandler httpHandler = toHttpHandler(serverResponseRouterFunction);
        // 转换为适配器
        ReactorHttpHandlerAdapter reactorHttpHandlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);
        // 创建HttpServer 设置端口
        HttpServer httpServer = HttpServer.create().port(8081);
        // 指定处理适配器并绑定
        DisposableServer disposableServer = httpServer.handle(reactorHttpHandlerAdapter).bindNow();
    }

    /**
     * 启动
     * @param args 参数
     */
    public static void main(String[] args) throws IOException {
        FunctionServer server = new FunctionServer();
        server.createReactorServer();
        System.out.println("enter to exit");
        int read = System.in.read();
    }

}
